﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using YouWei.Utility;
using YouWei.Utility.Logging;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 微信消息
    /// </summary>
    public class WxMessageController : ApiController
    {
        /// <summary>
        /// 接口认证
        /// </summary>
        /// <param name="echostr">随机字符串</param>
        /// <param name="signature">微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage Message(string echostr, string signature, string timestamp, string nonce)
        {
            string token = ConfigHelper.GetAppSettingValue("weixin.token");
            if (!CheckSignature(token, signature, timestamp, nonce))
                echostr = "验证不正确";
            HttpResponseMessage responseMessage = new HttpResponseMessage { Content = new StringContent(echostr, Encoding.GetEncoding("UTF-8"), "text/plain") };

            return responseMessage;
        }

        /// <summary>
        /// 接收客服消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage Message()
        {
            var content = Request.Content.ReadAsStringAsync();
            Log4netLog.Debug(content.Result);
            HttpResponseMessage responseMessage = new HttpResponseMessage();
            return responseMessage;
        }


        /// <summary>
        /// 验证微信签名
        /// </summary>
        private bool CheckSignature(string token, string signature, string timestamp, string nonce)
        {
          
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);

            Log4netLog.Debug(tmpStr);

            using (var sha1= SHA1.Create())
            {
                var data = sha1.ComputeHash(Encoding.UTF8.GetBytes(tmpStr));
                var sb = new StringBuilder();
                foreach (var t in data)
                {
                    sb.Append(t.ToString("X2"));
                }
                tmpStr = sb.ToString();
            }     
            tmpStr = tmpStr.ToLower();

            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
